package by.airlanterns.web;


import by.airlanterns.dto.*;
import by.airlanterns.dto.enums.Enum;
import by.airlanterns.service.*;
import org.apache.commons.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: DoorToTheMoon
 * Date: 28.01.13
 * Time: 19:28
 * To change this template use File | Settings | File Templates.
 */

@Controller
@RequestMapping(value = "admin")
public class SettingController extends BaseController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private LanternService lanternService;

    @Autowired
    private ActionService actionService;

    @Autowired
    private UserService userService;

    @Autowired
    private ContentPageService contentPageService;


    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showSettings() {
        Map<String, Object> model = getModel();
        model.put("lanterns", lanternService.getAllLanterns());
        model.put("category", categoryService.getAllCategories());
        model.put("users", userService.findAllUsers());

        return new ModelAndView("admin_header", model);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public void editLantent(HttpServletResponse response, HttpServletRequest request) {
        Integer lantentId = Integer.valueOf(request.getParameter("id"));
        Lantern lantern = lanternService.getLanternById(lantentId);

        Category category = categoryService.findCategoryById(Integer.valueOf(request.getParameter("cat_id")));

        if (lantern != null) {
            if (category != null) {
                lantern.setCategory(category);
            }

            lantern.setDescription(request.getParameter("description"));
            lantern.setImgUrl(request.getParameter("url"));
            lantern.setPrice(Integer.valueOf(request.getParameter("price")));
        }
    }

    @RequestMapping(value = "/addlantern", method = RequestMethod.POST)
    public ModelAndView addLantern(MultipartHttpServletRequest request, HttpServletResponse response) {

        Lantern lantern;
        if (request.getParameterMap().containsKey("id")) {
            lantern = lanternService.findById(Integer.parseInt(request.getParameter("id")));
        } else {
            lantern = new Lantern();
        }

        if (request.getParameterMap().containsKey("document_file")) {
            MultipartFile file = request.getFile("document_file");
            String link = uploadFile(file, request, "img/lanterns_image");
            lantern.setImgUrl(link);
        }

        lantern.setCategory(categoryService.findCategoryById(Integer.valueOf(request.getParameter("lanter_cat"))));
        lantern.setDescription(request.getParameter("description"));
        lantern.setPrice(Integer.valueOf(request.getParameter("price")));

        lanternService.saveOrUpdate(lantern);

        return new ModelAndView("redirect:/admin.html");
    }

    @RequestMapping(value = "/getlantern", method = RequestMethod.POST)
    private
    @ResponseBody
    Lantern getLantern(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("lantern_id"));
        return lanternService.findById(id);
    }

    @RequestMapping(value = "/removelantern", method = RequestMethod.POST)
    private void removeLantern(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("lantern_id"));
        Lantern lantern = lanternService.findById(id);
        lanternService.delete(lantern);
    }

    public String uploadFile(MultipartFile file, HttpServletRequest request, String path) {
        String fileName = "";
        try {

            InputStream inputStream;
            OutputStream outputStream;
            if (file.getSize() > 0) {
                inputStream = file.getInputStream();
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                Random random = new Random(calendar.getTimeInMillis());
                fileName = "/" + path + "/" + file.getOriginalFilename();
                String fullPath = request.getRealPath("") + fileName;
                outputStream = new FileOutputStream(fullPath);
                System.out.println("fileName:" + fullPath);
                int readBytes = 0;
                byte[] buffer = new byte[10000];
                while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
                    outputStream.write(buffer, 0, readBytes);
                }
                outputStream.close();
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    @RequestMapping(value = "/admin_action", method = RequestMethod.GET)
    public ModelAndView action() {
        return new ModelAndView("admin_action");
    }

    @RequestMapping(value = "/add_image", method = RequestMethod.POST)
    private ModelAndView addImage(FileUpload fileUpload, MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
        //FileUpload file = fileUpload;
        MultipartFile multipartFile = request.getFile("fileUpload");
        String fileName = uploadFile(multipartFile, request, "img/lanterns_image");
        System.out.println(fileName);
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("url", fileName);
        return new ModelAndView("/actions/add_image", model);
    }

    @RequestMapping(value = "/action_save", method = RequestMethod.POST)
    private void actionAdd(HttpServletRequest request, HttpServletResponse response) {
        String body = request.getParameter("elm2");
        String checkBox = request.getParameter("is_active");

        by.airlanterns.dto.enums.Enum isActive;

        if (checkBox != null && checkBox.equals("on")) {
            isActive = Enum.yes;
        } else {
            isActive = Enum.no;
        }

        SiteAction action;
        if (request.getParameterMap().containsKey("action_id")) {
            action = actionService.findById(Integer.parseInt(request.getParameter("action_id")));
        } else {
            action = new SiteAction();
        }
        action.setDescription(body);
        action.setActivated(isActive);
        actionService.savOrUpdate(action);
    }

    @RequestMapping(value = "/get_action", method = RequestMethod.POST)
    private
    @ResponseBody
    SiteAction getAction(HttpServletRequest request, HttpServletResponse response) {
//        Action action = actionService.findById(id);

//        if(request.getParameterMap().containsKey("action_id")) {
//            int id = Integer.parseInt(request.getParameter("action_id"));
//        }

        SiteAction action = actionService.getAction();
        if (action == null) {
            action = new SiteAction();
        }
        return action;
    }

    @RequestMapping(value = "/delete_user", method = RequestMethod.POST)
    private void removeUser(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("user_id"));
        User user = userService.findUserById(id);
        userService.deleteUser(user);
    }

    @RequestMapping(value = "/upload_page_content", method = RequestMethod.POST)
    private void uploadPageData(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.valueOf(request.getParameter("id"));
        ContentPage contentPage = contentPageService.getContentByPageId(id);
        contentPage.setContent(request.getParameter("content"));
        contentPageService.saveOrUpdateContent(contentPage);
    }

    @RequestMapping(value = "/get_content_page", method = RequestMethod.POST)
    private
    @ResponseBody
    ContentPage getContentPageData(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.valueOf(request.getParameter("id"));
        return contentPageService.getContentByPageId(id);
    }

    @RequestMapping(value = "/check_pswd", method = RequestMethod.POST)
    private
    @ResponseBody
    String checkPswd(HttpServletRequest request, HttpServletResponse response) {
        String paswd = request.getParameter("pswd");
        PasswordEncoder encoder = new Md5PasswordEncoder();
        String hashedPass = encoder.encodePassword(paswd, null);
        if (hashedPass.equals(getCurrentUser().getPassword())) {
            return "yes";
        }

        return "no";
    }

    @RequestMapping(value = "/change_pswd", method = RequestMethod.POST)
    private void changePSWD(HttpServletRequest request, HttpServletResponse response) {
        User user = getCurrentUser();
        String newPswd = request.getParameter("pswd");
        PasswordEncoder encoder = new Md5PasswordEncoder();
        String hashedPass = encoder.encodePassword(newPswd, null);
        user.setPassword(hashedPass);

        userService.saveOrUpdate(user);
    }

}
